package cn.xeyuan.mybatis;
import cn.xeyuan.mybatis.config.DataSourceConfig;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootApplication
//扫描mapper包
@MapperScan("cn.xeyuan.mybatis.mapper")
public class SpringBootMybatisApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootMybatisApplication.class, args);
	}
	@Bean
	@ConfigurationProperties(prefix = "datasource")
	public DataSourceConfig dataSourceConfig() {
		return new DataSourceConfig();
	}
	/**
	 * 注册DruidServlet
	 *
	 * @return
	 */
	@Bean
	public ServletRegistrationBean druidServletRegistrationBean() {
		ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
		servletRegistrationBean.setServlet(new StatViewServlet());
		servletRegistrationBean.addUrlMappings("/druid/*");
		return servletRegistrationBean;
	}
	/**
	 * 注册DruidFilter拦截
	 *
	 * @return
	 */
	@Bean
	public FilterRegistrationBean duridFilterRegistrationBean() {
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
		filterRegistrationBean.setFilter(new WebStatFilter());
		Map<String, String> initParams = new HashMap<String, String>();
		//设置忽略请求
		initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
		filterRegistrationBean.setInitParameters(initParams);
		filterRegistrationBean.addUrlPatterns("/*");
		return filterRegistrationBean;
	}
	/**
	 * 配置DataSource
	 * @return
	 * @throws SQLException
	 */
	@Bean
	public DataSource druidDataSource() throws SQLException {
		System.out.println("链接地址="+this.dataSourceConfig().getUrl());
		DruidDataSource druidDataSource = new DruidDataSource();
		druidDataSource.setUsername(dataSourceConfig().getUsername());
		druidDataSource.setPassword(dataSourceConfig().getPassword());
		druidDataSource.setUrl(dataSourceConfig().getUrl());
		druidDataSource.setDriverClassName(dataSourceConfig().getDriverClassName());
		//配置对emoji表情的支持
		List<String> list = new ArrayList<>();
		list.add("set names utf8mb4;");
		druidDataSource.setConnectionInitSqls(list);
		druidDataSource.setMaxActive(100);
		druidDataSource.setFilters("stat,wall");
		druidDataSource.setInitialSize(10);
		return druidDataSource;
	}
}
